package com.kuang.forkjoin;

import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author luomingliang
 * @date 2021/5/25 22:34
 */
public class DemoTest {

    @Test
    public void test01() {
        long startTime = System.currentTimeMillis();
        long sum = 0L;
        for (long i = 1L; i <= 10_0000_0000; i++) {
            sum += i;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("结果="+sum+", 用时："+(endTime - startTime));
    }

    //会使用ForkJoin
    @Test
    public void test02() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo task = new ForkJoinDemo(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task); //提交任务
        Long sum = submit.get();
        long endTime = System.currentTimeMillis();
        System.out.println("结果="+sum+", 用时："+(endTime - startTime));
    }

    @Test
    public void test03() {
        long startTime = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long endTime = System.currentTimeMillis();
        System.out.println("结果="+sum+", 用时："+(endTime - startTime));
    }
}
